package com.example.recyclerviewandcardview;

import java.util.List;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {

    private LayoutInflater inflater;
    private List<Post> postList;

    public PostAdapter(Context context, List<Post> postList) {
        inflater = LayoutInflater.from(context);
        this.postList = postList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = inflater.inflate(R.layout.activity_main_item, parent, false);
        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Post post = postList.get(position);
        holder.board.setBackgroundColor(post.getBackgroundColor());
        holder.img.setImageResource(post.getImgResId());
        holder.tvTitle.setText(post.getTitle());
        holder.tvSummary.setText(post.getSummary());
    }

    @Override
    public int getItemCount() {
        return postList == null ? 0 : postList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public View board;
        public ImageView img;
        public TextView tvTitle;
        public TextView tvSummary;

        public ViewHolder(View itemView) {
            super(itemView);
            board = itemView.findViewById(R.id.board);
            img = (ImageView) itemView.findViewById(R.id.img);
            tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
            tvSummary = (TextView) itemView.findViewById(R.id.tv_summary);
            itemView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View view) {
                    postList.add(postList.remove(getPosition()));
                    PostAdapter.this.notifyItemMoved(getPosition(), postList.size() - 1);
                }

            });
        }

    }

}
